package com.lccviolet;

import java.util.concurrent.TimeUnit;

/**
 * @author LiChaochao
 * @Date 2021/9/21 8:58
 * @Description 死锁案例：指两个或两个以上的进程在执行过程中，因争夺资源而造成的一种互相等待的现象
 *
 * 排查错误命令cmd：
 *      jps -f：同linux ps -ef | grep，定位进程号
 *      jstack 端口号：打印进程信息
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";

        new Thread(new HoldLockThread(lockA, lockB), "t1").start();
        new Thread(new HoldLockThread(lockB, lockA), "t2").start();
    }
}

class HoldLockThread implements Runnable {

    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() + "持有锁" + lockA + "，尝试获得" + lockB);
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "持有锁" + lockB + "，尝试获得" + lockA);
            }
        }
    }
}
